<template>
  <div class="exam-room-container">
    <h2>考场布置</h2>

    <!-- 主体内容部分 -->
    <div class="content">
      <!-- 学生查看考试安排 -->
      <div class="view-exams">
        <h3>查看考试安排</h3>
        <table>
          <thead>
            <tr>
              <th>考场号</th>
              <th>考试时间</th>
              <th>课程名称</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="exam in examList" :key="exam.examId">
              <td>{{ exam.roomNumber }}</td>
              <td>{{ formatDate(exam.examTime) }}</td>
              <td>{{ exam.courseName }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 考试安排表单 -->
      <div class="arrange-exam">
        <h3>发布考试通知</h3>
        <form @submit.prevent="arrangeExam">
          <div class="input-group">
            <label for="roomNumber">考场号:</label>
            <input v-model="roomNumber" id="roomNumber" type="text" placeholder="请输入考场号" required />
          </div>
          <div class="input-group">
            <label for="examTime">考试时间:</label>
            <input 
              v-model="examTime" 
              id="examTime" 
              type="datetime-local" 
              :min="minExamTime"
              required 
            />
          </div>
          <div class="input-group">
            <label for="isRandom">是否随机安排座位:</label>
            <select v-model="isRandom" id="isRandom" required>
              <option value="yes">是</option>
              <option value="no">否</option>
            </select>
          </div>
          <button type="submit" :disabled="!roomNumber || !examTime">发布考试</button>
        </form>
        <p v-if="message" :class="{ success: successMessage, error: !successMessage }">{{ message }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ExamRoomSetup',
  data() {
    return {
      courseId: this.$route.params.courseId, // 获取课程ID
      roomNumber: '', // 考场号
      examTime: '', // 考试时间
      isRandom: 'no', // 是否随机安排座位（默认为不随机）
      message: '', // 发布结果
      successMessage: false, // 控制消息显示的类型
      examList: [], // 存储考试安排的列表
    };
  },
  computed: {
    // 获取最小考试时间（当前时间）
    minExamTime() {
      const now = new Date();
      now.setMinutes(now.getMinutes() - now.getTimezoneOffset()); // 修正时区偏差
      return now.toISOString().slice(0, 16); // 返回格式: yyyy-MM-ddThh:mm
    },
  },
  mounted() {
    const studentId = 123; // 假设学生ID为123，应该从真实的学生登录状态中获取
    this.fetchExamList(studentId);
  },
  methods: {
    // 发布考试通知
    arrangeExam() {
      // 格式化 examTime 为 yyyy-MM-dd HH:mm:ss 格式
      const formattedExamTime = this.formatExamTime(this.examTime);

      const examData = {
        roomNumber: this.roomNumber,
        courseId: this.courseId,
        examTime: formattedExamTime, // 格式化后的时间
        isRandom: this.isRandom, // 是否随机安排
      };

      console.log(examData);  // 调试输出数据

      axios
        .post('http://localhost:8085/exam/arrangeexam', null, { 
          params: examData 
        })
        .then(response => {
          this.message = response.data;
          this.successMessage = true; // 发布成功
          this.roomNumber = '';
          this.examTime = '';
        })
        .catch(error => {
          this.message = `发布考试失败: ${error.response ? error.response.data : error.message}`;
          this.successMessage = false; // 发布失败
        });
    },

    // 格式化日期：将 `examTime` 转换为 `yyyy-MM-dd HH:mm:ss` 格式
    formatExamTime(examTime) {
      const date = new Date(examTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 获取学生的考试安排
    fetchExamList(studentId) {
      axios
        .get('http://localhost:8085/exam/teacherviewexam', { 
          params: { courseId: this.courseId } // 获取教师的考试安排
        })
        .then(response => {
          this.examList = response.data; // 更新考试安排列表
        })
        .catch(error => {
          console.error('获取考试安排失败:', error);
        });
    },

    // 格式化考试时间（使其更加友好）
    formatDate(dateString) {
      const date = new Date(dateString);
      const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
      return date.toLocaleString('zh-CN', options); // 本地化格式化
    },
  },
};
</script>

<style scoped>
.exam-room-container {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fafafa;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 1000px;
  margin: 30px auto;
}

h2 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.content {
  display: flex;
  justify-content: space-between;
  gap: 30px;
}

.view-exams {
  flex: 2;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.arrange-exam {
  flex: 1;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h3 {
  font-size: 24px;
  color: #555;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

table th,
table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

input, select, button {
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 100%;
  box-sizing: border-box;
}

button {
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
  margin-top: 15px;
  transition: background-color 0.3s;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:enabled {
  background-color: #45a049;
}

p {
  margin-top: 10px;
  font-size: 16px;
}

p.success {
  color: #28a745;
}

p.error {
  color: #dc3545;
}
</style>
